import os

from PIL import Image


def convert_img(folder_path, source_format):
    """将指定文件夹中的图片文件转换为 jpg 格式

    Args:
        folder_path (str): 目标文件夹路径
        source_format (str): 源文件格式，例如 '.webp' 或 '.png'

    Returns:
        bool: 是否全部转换成功
    """
    success_count = 0
    error_count = 0

    for root, _, files in os.walk(folder_path):
        target_files = [f for f in files if f.lower().endswith(source_format)]
        total_files = len(target_files)

        if total_files == 0:
            return True

        print(f"   发现 {total_files} 个{source_format}文件")

        for index, file in enumerate(target_files, 1):
            try:
                image_path = os.path.join(root, file)
                img = Image.open(image_path)

                if img.mode in ('RGBA', 'LA', 'P'):
                    img = img.convert('RGB')

                jpg_path = os.path.splitext(image_path)[0] + '.jpg'
                img.save(jpg_path, 'JPEG', quality=95)
                img.close()
                os.remove(image_path)

                success_count += 1
                print(f"   [{index}/{total_files}] 转换成功: {file}")
            except Exception as e:
                error_count += 1
                print(f"   !! [{index}/{total_files}] 转换失败: {file}")
                print(f"   !! 错误信息: {e}")

    if error_count > 0:
        print(f"   -- 转换完成: 成功 {success_count} 个, 失败 {error_count} 个")
        return False
    return True


def has_img_files(folder_path, format_type):
    """检查文件夹中是否存在指定格式的图片文件

    Args:
        folder_path (str): 目标文件夹路径
        format_type (str): 文件格式，例如 '.webp' 或 '.png'

    Returns:
        bool: 是否存在指定格式的文件
    """
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith(format_type):
                return True
    return False
